package server.handler;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.List;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class SelectionKeyHandlerChain {

    private static final Integer BUFFER_LENGTH = 1024;

    private Selector selector;
    protected ByteBuffer writeBuffer;
    protected ByteBuffer readBuffer;

    private List<AbstractSelectionKeyHandler> handlers;

    {
        handlers = new ArrayList<AbstractSelectionKeyHandler>() {
            {
                add(new AcceptHandlerAbstract());
                add(new ReadHandler());
                add(new WriteHandler());
            }
        };
    }

    public SelectionKeyHandlerChain(Selector selector) {
        this.selector = selector;
        this.writeBuffer = ByteBuffer.allocate(BUFFER_LENGTH);
        this.readBuffer = ByteBuffer.allocate(BUFFER_LENGTH);
    }

    public void consumer(SelectionKey selectionKey) {
        for (AbstractSelectionKeyHandler handler : handlers) {
            handler.config(selector, readBuffer, writeBuffer);
            handler.execute(selectionKey);
        }
    }

}
